package models

import play.api.db._
import play.api.Play.current

import anorm._
import anorm.SqlParser._

case class ShopOwner(email: String, name: String, password: String)

object ShopOwner {


  // -- Parsers

  /**
   * Parse a User from a ResultSet
   */
  val simple = {
    get[String]("owner.email") ~
      get[String]("owner.name") ~
      get[String]("owner.password") map {
      case email ~ name ~ password => ShopOwner(email, name, password)
    }
  }

  // -- Queries

  /**
   * Retrieve a User from email.
   */
  def findByEmail(email: String): Option[ShopOwner] = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from owner where email = {email}").on(
          'email -> email
        ).as(ShopOwner.simple.singleOpt)
    }
  }

  /**
   * Retrieve all users.
   */
  def findAll: Seq[ShopOwner] = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from owner").as(ShopOwner.simple *)
    }
  }

  /**
   * Authenticate a User.
   */
  def authenticate(email: String, password: String): Option[ShopOwner] = {
    DB.withConnection {
      implicit connection =>
        SQL(
          """
           select * from owner where
           email = {email} and password = {password}
          """
        ).on(
          'email -> email,
          'password -> password
        ).as(ShopOwner.simple.singleOpt)
    }
  }

  /**
   * Create a User.
   */
  def create(user: ShopOwner): ShopOwner = {
    DB.withConnection {
      implicit connection =>
        SQL(
          """
            insert into owner values (
              {email}, {name}, {password}
            )
          """
        ).on(
          'email -> user.email,
          'name -> user.name,
          'password -> user.password
        ).executeUpdate()

        user

    }
  }

  def delete(email: String): Boolean = {
    DB.withConnection {
      implicit connection =>
        SQL(
          """
             delete from owner where email = {email}
          """
        ).on(
          'email -> email
        ).executeUpdate()
        true
    }
  }

  def update(owner: ShopOwner): ShopOwner = {
    DB.withConnection {
      implicit connection =>
        SQL(
          """
            update owner set
              name = {name},
              password = {password}
            where email = {email}
          """
        ).on(
          'email -> owner.email,
          'name -> owner.name,
          'password -> owner.password
        ).executeUpdate()

        owner
    }
  }

}
